package com.link.base.base.order.service;

import com.link.base.base.order.dao.mybatis.mapper.SaleOrderItemMapper;
import com.link.base.base.order.model.ArrivalDetails;
import com.link.base.base.order.model.SaleOrderItem;
import com.link.base.base.product.model.Product;
import com.link.base.base.product.service.ProductService;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.ServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.cllog.LCLogger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author unknown
 * @date unknown
 * @comments 定单行服务
 */
@Service
public class SaleOrderItemServiceImpl extends BasicServiceImpl<SaleOrderItem> implements SaleOrderItemService {

    @Resource
    private SaleOrderItemMapper saleOrderItemMapper;

    @Resource
    private ProductService productService;

    @Override
    public BasicMapper<SaleOrderItem> getBasicMapper() {
        return saleOrderItemMapper;
    }

    @Override
    public List<SaleOrderItem> querylistByOrderId(Long orderId) throws Exception {
        SaleOrderItem orderItemExample = new SaleOrderItem();
        orderItemExample.setPageFlag(false);
        orderItemExample.setHeadId(orderId);
        return saleOrderItemMapper.queryByExamplePage(orderItemExample);
    }

    @Override
    public List<SaleOrderItem> querylistByOrderId(Long orderId, String type) throws Exception {
        SaleOrderItem orderItemExample = new SaleOrderItem();
        orderItemExample.setPageFlag(false);
        orderItemExample.setHeadId(orderId);
        if (type == null || "".equals(type)) {
            throw new ServiceException("ORDER-017");
        }
        String endStr = "!";
        if (type.startsWith(endStr)) {
            type = type.substring(1);
            orderItemExample.setAttr3(type);
        } else {
            orderItemExample.setAttr4(type);
        }
        return saleOrderItemMapper.queryByExamplePage(orderItemExample);
    }

    @Override
    public void qtyUpdate(SaleOrderItem record) throws ServiceException {
        try {
            saleOrderItemMapper.qtyUpdate(record);
        } catch (Exception e) {
            LCLogger.withException(e);
            throw new ServiceException(e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void insertDmsOrderItem(Long orgId, Long acctId, Long headId, List<SaleOrderItem> list) throws Exception {
        if (headId == null) {
            throw new ServiceException("ORDER-018");
        }
        for (int i = 0; i < list.size(); i++) {
            Product product = new Product();
            SaleOrderItem orderItem = list.get(i);
            Long prodId = orderItem.getProdId();
            product.setId(prodId);
            product.setAcctId(acctId);
            product.setxAttr03(orgId);
            //重新查询获取价格
            product = productService.queryProdWithAcctPriceById(product);
            if (product != null) {
                orderItem.setId(keyGenerateService.keyGenerate());
                orderItem.setHeadId(headId);
                orderItem.setBasePrice(product.getPrice());
                orderItem.setPromotionPrice(product.getPromoPrice());
                orderItem.setNetPrice(product.getPromoPrice());
                orderItem.setItemType("Common Item");
                this.insert(orderItem);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void updateDmsOrderItem(Long acctId, Long headId, List<SaleOrderItem> list) throws Exception {
        if (acctId == null) {
            throw new ServiceException("PUBLIC-026");
        }
        if (headId == null) {
            throw new ServiceException("ORDER-018");
        }
        SaleOrderItem item = new SaleOrderItem();
        item.setHeadId(headId);
        item.setAttr4("Common Item");
        item.setPageFlag(false);
        List<SaleOrderItem> queryItems = saleOrderItemMapper.queryByExamplePage(item);
        for (int i = 0; i < list.size(); i++) {
            SaleOrderItem orderItem = list.get(i);
            boolean flag = false;
            for (int j = 0; queryItems != null && j < queryItems.size(); j++) {
                SaleOrderItem queryItem = queryItems.get(j);
                if (orderItem.getProdId() != null && orderItem.getProdId().equals(queryItem.getProdId())) {
                    //产品id相等
                    if (orderItem.getQty().doubleValue() != queryItem.getQty().doubleValue()) {
                        //数量不等则更新数量
                        queryItem.setQty(orderItem.getQty());
                        //更新数量
                        saleOrderItemMapper.qtyUpdate(queryItem);
                    }
                    //保留
                    queryItem.setAttr1("keep");
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                //该订单行为新行
                Product product = new Product();
                Long prodId = orderItem.getProdId();
                product.setId(prodId);
                product.setAcctId(acctId);
                //重新查询获取价格
                product = productService.queryProdWithAcctPriceById(product);
                if (product != null) {
                    orderItem.setId(keyGenerateService.keyGenerate());
                    orderItem.setHeadId(headId);
                    orderItem.setBasePrice(product.getPrice());
                    orderItem.setPromotionPrice(product.getPromoPrice());
                    orderItem.setNetPrice(product.getPromoPrice());
                    orderItem.setItemType("Common Item");
                    this.insert(orderItem);
                }
            }
        }

        //删除多余行
        for (int i = 0; queryItems != null && i < queryItems.size(); i++) {
            SaleOrderItem queryItem = queryItems.get(i);
            if (!"keep".equals(queryItem.getAttr1())) {
                saleOrderItemMapper.deleteById(queryItem);
            }
        }
    }

    @Override
    public void deleteByOrderRuleProdId(SaleOrderItem itemExample) throws Exception {
        if (itemExample.getHeadId() == null) {
            throw new ServiceException("ORDER-018");
        }
        if (itemExample.getPolicyResultId() == null) {
            throw new ServiceException("ORDER-019");
        }
        if (itemExample.getProdId() == null) {
            throw new ServiceException("ORDER-019");
        }
        saleOrderItemMapper.deleteByOrderRuleProdId(itemExample);
    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void insertPcyOrderItem(List<SaleOrderItem> list) throws Exception {
        if (list == null || list.size() == 0) {
            throw new ServiceException("ORDER-020");
        }
        for (int i = 0; i < list.size(); i++) {
            SaleOrderItem item = list.get(i);
            if (item.getHeadId() == null) {
                throw new ServiceException("ORDER-018");
            }
            if (item.getPolicyResultId() == null) {
                throw new ServiceException("ORDER-019");
            }
            if (item.getPolicyRuleId() == null) {
                throw new ServiceException("ORDER-021");
            }
            if (item.getProdId() == null) {
                throw new ServiceException("ORDER-022");
            }
            if (item.getItemType() == null) {
                throw new ServiceException("ORDER-023");
            }
            if (item.getQty() == null || item.getQty() <= 0) {
                throw new ServiceException("ORDER-024");
            }
        }
        SaleOrderItem example = new SaleOrderItem();
        example.setPageFlag(false);
        example.setHeadId(list.get(0).getHeadId());
        //不等于Common Item
        example.setAttr3("Common Item");
        List<SaleOrderItem> queryItems = saleOrderItemMapper.queryByExamplePage(example);

        for (int i = 0; i < list.size(); i++) {
            SaleOrderItem orderItem = list.get(i);
            boolean flag = false;
            for (int j = 0; queryItems != null && j < queryItems.size(); j++) {
                SaleOrderItem queryItem = queryItems.get(j);
                if (orderItem.getPolicyResultId().equals(queryItem.getPolicyResultId())) {
                    //规则结果id相等，可能为多余的订单行，设置标记
                    queryItem.setAttr1("delete");
                    if (orderItem.getProdId().equals(queryItem.getProdId())) {
                        //产品id相等，已有订单行，需要保留
                        if (orderItem.getQty().doubleValue() != queryItem.getQty().doubleValue()) {
                            //数量不等，整行更新
                            orderItem.setId(queryItem.getId());
                            //更新
                            saleOrderItemMapper.update(orderItem);
                        }
                        //保留
                        queryItem.setAttr1("keep");
                        //非新行标记
                        flag = true;
                        break;
                    }
                }
            }

            if (!flag) {
                //该订单行为新行
                orderItem.setId(keyGenerateService.keyGenerate());
                this.insert(orderItem);
            }
        }
        //删除多余行
        for (int i = 0; queryItems != null && i < queryItems.size(); i++) {
            SaleOrderItem queryItem = queryItems.get(i);
            if ("delete".equals(queryItem.getAttr1())) {
                saleOrderItemMapper.deleteById(queryItem);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void deepCopyOrderItem(Long sourceOrderId, Long targetOrderId) throws Exception {
        if (sourceOrderId == null) {
            throw new ServiceException("ORDER-025");
        }
        if (targetOrderId == null) {
            throw new ServiceException("ORDER-026");
        }
        SaleOrderItem example = new SaleOrderItem();
        example.setPageFlag(false);
        example.setHeadId(sourceOrderId);

        List<SaleOrderItem> items = saleOrderItemMapper.queryByExamplePage(example);

        for (int i = 0; items != null && i < items.size(); i++) {
            SaleOrderItem item = items.get(i);
            item.setHeadId(targetOrderId);
            item.setId(keyGenerateService.keyGenerate());
            saleOrderItemMapper.insert(item);
        }
    }

    @Override
    public void prodCumulateSaleAdd(SaleOrderItem entity) {
        saleOrderItemMapper.prodCumulateSaleAdd(entity);
    }

    @Override
    public void prodCumulateSaleSub(SaleOrderItem entity) {
        saleOrderItemMapper.prodCumulateSaleSub(entity);
    }

    @Override
    public void prodCumulateSale(SaleOrderItem saleOrderItem) {
        saleOrderItemMapper.prodCumulateSale(saleOrderItem);
    }

    /**
     * 获取到货列表
     *
     * @param arrivalDetails
     * @return
     * @throws Exception
     */
    @Override
    public List<ArrivalDetails> queryArriDetailsByPage(ArrivalDetails arrivalDetails) throws Exception {
        List<ArrivalDetails> list = saleOrderItemMapper.queryArriDetailsByPage(arrivalDetails);
        return list;
    }

    /**
     * 查询当前登录导购某天产品销售情况
     *
     * @author Lizt
     */
    @Override
    public List<SaleOrderItem> querySaleProduct(SaleOrderItem saleOrderItem) throws Exception {
        return saleOrderItemMapper.querySaleProduct(saleOrderItem);
    }
}
